<?php

namespace app\admin\controller;

use app\admin\validate\SysDictData as SysDictDataValidate;
use app\common\business\SysDictData as SysDictDataBus;
use app\common\business\SysDictType as SysDictTypeBus;
use app\common\lib\toCamelCase;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class SysDictData extends AuthBase
{
    //根据字典类型查询字典数据信息
    public function data(){
        try {
            $dictType = $this->request->param("type","","trim");
            if(empty($dictType)){
                $DictData = [];
            }else{
                $DictData = (new SysDictDataBus())->getDictData($dictType);
                $DictData = (new toCamelCase())->toCamelCaseArray($DictData);
            }
        }catch (\Exception $e){
            $DictData = [];
        }
        return show(config("status.success"),"字典数据列表",$DictData);
    }

    //获取字典类型数据列表查询条件
    public function dictDataListSearch(){
        $where = [];
        // 获取分页参数
        $page = $this->request->param('pageNum', 1);
        $limit = $this->request->param('pageSize', 10);
        $dictLabel = $this->request->param('dictLabel',"");
        $dictType = $this->request->param('dictType',"");
        $status = $this->request->param("status","");
        if($dictLabel){
            $where[] = ['dict_label', 'like', '%'.$dictLabel.'%'];
        }
        if($dictType){
            $where[] = ['dict_type', '=', $dictType];
        }
        if ($status !== null && $status !== '') {
            // 如果$status不为null且不为空字符串，则添加条件到$where数组
            $where[] = ["status", "=", $status];
        }
        $data = [
            'page'=>$page,
            'limit'=>$limit,
            'where'=>$where,
        ];
        return $data;
    }

    //字典类型数据列表
    public function dataList(){
        $searchData = $this->dictDataListSearch();
        try {
            $dictTypeData = (new SysDictDataBus)->getNormalDictData($searchData['where'],'*',$searchData['limit'],$searchData['page']);
            $dictTypeData = (new toCamelCase())->toCamelCaseArray($dictTypeData);
        }catch (\Exception $e){
            $dictTypeData = [];
        }
        return show(config("status.success"),"字典类型数据列表",$dictTypeData);
    }

    //字典类型数据添加
    public function dictDataAdd(){
        if (!$this->request->isPost()){
            return show(config("status.error"),"请求方式错误");
        }
        //参数校验
        $allParams = request()->param();
        $data = (new toCamelCase())->toCamelCaseArray($allParams,'1',2);
        $validate = new SysDictDataValidate();
        if(!$validate->check($data)){
            return show(config("status.error"),$validate->getError());
        }
        try {
            $result = (new SysDictDataBus())->addDictData($data);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"新增成功",$result);
    }

    //字典类型数据修改
    public function dictDataEdit(){
        $allParams = request()->param();
        $data = (new toCamelCase)->toCamelCaseArray($allParams,1,2);
        try {
            $result = (new SysDictDataBus())->updateById($data['dict_code'],$data);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"修改成功",$result);
    }

    //字典类型数据详情
    public function dictDataDetails(){
        $data = $this->request->param("data","","trim");
        if(empty($data)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $dictData = (new SysDictDataBus())->getDictDataById($data);
            $dictData = (new toCamelCase())->toCamelCaseArray($dictData);
        }catch (\Exception $e){
            $dictData = [];
        }
        return show(config("status.success"),"字典类型数据详情",$dictData);
    }

    //删除字典类型
    public function dictDataDel(){
        $data = $this->request->param("data","","trim");
        if(empty($data)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $result = (new SysDictDataBus())->DeldictDataIds($data);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"删除成功",$result);
    }

    //导出字典类型数据信息
    public function exportDictData(){
        $searchData = $this->dictDataListSearch();
        $dictTypeData = (new SysDictDataBus)->getNormalDictData($searchData['where'],'*',$searchData['limit'],$searchData['page']);
        $dictType = $this->request->param('dictType',"");
        $dictTypeName =(new SysDictTypeBus())->getDictByType($dictType);
        // 创建Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $sheet->mergeCells('A1:H1'); // 假设表头只有5列
        $sheet->setCellValue('A1', '字典类型数据信息');
        // 设置表头
        $header = ['字典编码', '字典名称', '字典标签', '字典键值', '字典排序','状态','备注','创建时间'];
        $row = 2;
        $col = 1; // 列索引，从A列开始
        foreach ($header as $column) {
            // 使用setCellValueByColumnAndRow时，第二个参数是列号（整数），第三个参数是值
            $sheet->setCellValueByColumnAndRow($col, $row, $column);
            $col++; // 移动到下一列
        }
        // 使用循环设置列宽
        $columns = ['A', 'B', 'C', 'D', 'E', 'F','G','H']; // 定义需要设置宽度的列
        foreach ($columns as $column) {
            $sheet->getColumnDimension($column)->setWidth(18);
        }
        // 填充数据
        $row = 3;
        foreach ($dictTypeData['data'] as $post) {
            $post['status'] = $post['status'] === '0' ? "正常" : "停用";
            $sheet->setCellValue('A' . $row, $post['dict_code']);
            $sheet->setCellValue('B' . $row, $dictTypeName['dict_name']);
            $sheet->setCellValue('C' . $row, $post['dict_label']);
            $sheet->setCellValue('D' . $row, $post['dict_value']);
            $sheet->setCellValue('E' . $row, $post['dict_sort']);
            $sheet->setCellValue('F' . $row, $post['status']);
            $sheet->setCellValue('G' . $row, $post['remark']);
            $sheet->setCellValue('H' . $row, $post['create_time']);
            // 填充其他字段
            $row++;
        }
        $row = $row-1;
        $SpreadsheetObj = new \app\common\lib\Spreadsheet();
        $sheet->getStyle('A1')->applyFromArray($SpreadsheetObj->fontArray('FF000000',18));
        $sheet->getStyle('A2:H2')->applyFromArray($SpreadsheetObj->fillArray("808080"));
        $sheet->getStyle('A2:H2')->applyFromArray($SpreadsheetObj->fontArray("FFFFFFFF"));
        $sheet->getStyle('A1' . ':H' . $row)->applyFromArray($SpreadsheetObj->styleBorderArray());
        $sheet->getStyle('A1' . ':H' . $row)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

        // 创建Writer对象，并保存为xlsx文件
        $writer = new Xlsx($spreadsheet);
        // 设置响应头
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="post.xlsx"');
        header('Cache-Control: max-age=0');
        // 导出
        $writer->save('php://output');
        exit;
    }
}
